package service

import (
	"admin100/app/dao"
	"admin100/app/model"
	"admin100/app/service/broadcast"
	"admin100/library/define"
	"admin100/library/define/defErr"
	"admin100/library/utils"
	"strings"

	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/os/gcron"
	"github.com/gogf/gf/os/gtime"
	"github.com/gogf/gf/util/gconv"
)

var NoticeLog = &noticeLogService{}

type noticeLogService struct{}

func (s *noticeLogService) CloseCronNotice(uid int, ids []string) {
	notices, err := dao.NoticeLog.FindAll(dao.NoticeLog.Columns.Id, ids)
	defErr.SelectRetPanic(err, notices, define.DataOptFail)

	for _, id := range ids {
		gcron.Remove(dao.NoticeLog.GetCronName(gconv.Int(id)))
	}

	var curTime = gtime.Now().Unix()
	for _, v := range notices {
		v.Time = int(curTime)
		v.UserId = uid
		v.Status = 1
	}
	if _, err := dao.NoticeLog.Update(notices); err != nil {
		defErr.Panic(define.DataOptFail, err.Error())
	}
}

func (s *noticeLogService) DelNoticeLog(ids []string) {
	for _, id := range ids {
		gcron.Remove(dao.NoticeLog.GetCronName(gconv.Int(id)))
	}
	if _, err := dao.NoticeLog.Where(dao.NoticeLog.Columns.Id, ids).Delete(); err != nil {
		defErr.Panic(define.DataOptFail, err.Error())
	}
}

func (s *noticeLogService) GetNoticeLogList(req *model.NoticeLogReq) ([]*model.NoticeLog, int) {
	column := dao.NoticeLog.Columns

	//
	m := dao.NoticeLog.Where(g.Map{
		column.PlatformId: req.PlatformId,
		column.NoticeType: req.NoticeType,
	})
	if req.IsShowFinish == "0" {
		m = m.Where(column.Status, 0)
	}
	m2 := m.Clone()
	m.M = m.M.Order(column.Time + " desc")
	data, err := m.Page(req.Cur, req.PNum).FindAll()
	defErr.SelectRetPanic(err, data, define.DataOptFail)
	total, err := m2.Count()
	defErr.SelectRetPanic(err, total, define.DataOptFail)

	for _, e := range data {
		u, err := dao.MyadminUser.FindOne(dao.MyadminUser.Columns.Id, e.UserId)
		defErr.SelectRetPanic(err, u, define.DataOptFail)
		e.UserName = u.Name
	}

	return data, total
}

func (s *noticeLogService) CreateNoticeLog(req *model.SendNoticeReq, user *model.MyadminUser) bool {
	if !utils.CheckCronTimeStr(req.CronTimeStr) {
		defErr.Panic(define.FormatErrCronTime)
	}
	var (
		nowTs           = gconv.Int(gtime.TimestampStr())
		noticeLog       = &model.NoticeLog{}
		column          = dao.NoticeLog.Columns
		err             error
		serverIdListStr = ""
	)
	if req.Id > 0 {
		noticeLog, err = dao.NoticeLog.FindOne(column.Id, req.Id)
		if err != nil {
			defErr.Panic(define.DataOptFail, err.Error())
		}
	}
	//空格已经被中间件过滤掉了
	if req.ServerIdList != "" {
		serverIdListArr := strings.Split(req.ServerIdList, ",")
		serverIdListStr = "[\"" + strings.Join(serverIdListArr, "\",\"") + "\"]"
	}

	if noticeLog == nil || (noticeLog != nil && noticeLog.Id < 1) {
		//不存在
		noticeLog = &model.NoticeLog{
			PlatformId:     req.PlatformId,
			ServerIdList:   serverIdListStr,
			IsAllServer:    req.IsAllServer,
			Content:        req.Content,
			CreateCronTime: nowTs,
			Time:           nowTs,
			CreateUserId:   user.Id,
			UserId:         user.Id,
			NoticeType:     req.NoticeType,
			NoticeTime:     req.NoticeTime,
			CronTimeStr:    req.CronTimeStr,
			CronTimes:      req.CronTimes,
			Status:         0,
		}
	} else {
		noticeLog.PlatformId = req.PlatformId
		noticeLog.ServerIdList = serverIdListStr
		noticeLog.IsAllServer = req.IsAllServer
		noticeLog.Content = req.Content
		noticeLog.Time = nowTs
		noticeLog.UserId = user.Id
		noticeLog.NoticeType = req.NoticeTime
		noticeLog.NoticeTime = req.NoticeTime
		noticeLog.CronTimeStr = req.CronTimeStr
		noticeLog.CronTimes = req.CronTimes
	}
	if res, err := dao.NoticeLog.FieldsEx("userName").Save(noticeLog); err != nil {
		defErr.Panic(define.DataOptFail, err.Error())
	} else {
		newId, err := res.LastInsertId()
		if err != nil {
			defErr.Panic(define.DataOptFail, err.Error())
		}

		req.Id = int(newId)
	}

	gcron.Remove(dao.NoticeLog.GetCronName(req.Id))
	return broadcast.Broadcast.StartNoticeLog(req.Id)
}
